# -*- coding: UTF-8 -*-
"""
@Time : 2022/12/11
@Author : Gloria
"""
from django import forms
from markdown import markdown
from pyquery import PyQuery
import random
from app01.models import Cover

# 添加或编辑文章的验证
class AddArticleForm(forms.Form):
    title = forms.CharField(error_messages={'required': '请输入文章标题'})
    content = forms.CharField(error_messages={'required': '请输入文章内容'})
    abstract = forms.CharField(required=False)  # 不进行为空验证
    cover_id = forms.IntegerField(required=False)  # 不进行为空验证

    category = forms.IntegerField(required=False)
    pwd = forms.CharField(required=False)
    recommend = forms.BooleanField(required=False)
    status = forms.IntegerField(required=False)

    # 重写init方法
    # def __init__(self, *args, **kwargs):
    #     # 做自己想做的事情
    #     self.request = kwargs.pop('request', None)
    #     self.add_or_edit = kwargs.pop('add_or_edit', True)
    #     super().__init__(*args, **kwargs)

    # 全局钩子 分类 文章密码
    # def clean(self):
    #     category = self.cleaned_data['category']
    #     if not category:
    #         self.cleaned_data.pop('category')
    #
    #     pwd = self.cleaned_data['pwd']
    #     if not pwd:
    #         self.cleaned_data.pop('pwd')

    # 文章简介
    def clean_abstract(self):
        abstract = self.cleaned_data['abstract']
        if abstract:
            return abstract
        # 截取正文前30个字符
        content = self.cleaned_data.get('content')
        if content:
            abstract = PyQuery(markdown(content)).text()[:30]
            return abstract

    # 文章封面
    def clean_cover_id(self):
        cover_id = self.cleaned_data['cover_id']
        if cover_id:
            return cover_id
        cover_set = Cover.objects.all().values('nid')
        cover_id = random.choice(cover_set)['nid']
        return cover_id

    # def clean_category(self):
    #     category = self.cleaned_data['category']
    #     if not category:
    #         category = None
    #     return category

    # 获取文章的字符个数
    def clean_word(self):
        return len(self.cleaned_data.get('content', ''))

    # 文章简介
    # def clean_status(self):
    #     status = self.cleaned_data['status']
    #     print(status)